package com.ibm.psbc.cloud;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FeignClientFactoryBean;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.cloud.openfeign.Targeter;

import feign.Feign.Builder;
import feign.Request;
import feign.RequestTemplate;
import feign.Target;
import feign.Target.HardCodedTarget;

public class RouteTargeter implements Targeter {
	/**
	 * 服务名以本字符串结尾的，会被置换为实现定位到的单元号
	 */
	public static final String CLUSTER_ID_SUFFIX = "CLUSTER_ID";
	public static final String UINIT_ID_SUFFIX = "UNIT_ID";

	@Override
	public <T> T target(FeignClientFactoryBean factory, Builder feign, FeignContext context,
			HardCodedTarget<T> target) {

		return feign.target(new RouteTarget<>(target));
	}

	public static class RouteTarget<T> implements Target<T> {
		Logger log = LoggerFactory.getLogger(getClass());
		private Target<T> realTarget;

		public RouteTarget(Target<T> realTarget) {
			super();
			this.realTarget = realTarget;
		}

		@Override
		public Class<T> type() {
			return realTarget.type();
		}

		@Override
		public String name() {
			log.debug("name here:{}", realTarget.name());
			return realTarget.name();
		}

		@Override
		public String url() {
			String url = realTarget.url();
			if (url.endsWith(CLUSTER_ID_SUFFIX)) {
				url = url.replace(CLUSTER_ID_SUFFIX, locateCusterId());
				log.debug("url changed from {} to {}", realTarget.url(), url);
			}
			return url;
		}

		/**
		 * @return 定位到的实际单元号
		 */
		private String locateUnitId() {
			return "000";
		}

		/**
		 * @return 定位到的IDC号
		 */
		private String locateCusterId() {
			return "DC1";
		}

		@Override
		public Request apply(RequestTemplate input) {
			if (input.url().indexOf("http") != 0) {
				input.target(url());
			}
			return input.request();

		}

	}
}